package com.ww.springboot.dd.controller;

import java.io.*;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ImageDownloaderAndZipper2 {

    public static byte[] downloadImage(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        try (InputStream is = url.openStream();
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            byte[] imageBytes = baos.toByteArray();
            System.out.println("图片数据长度: " + imageBytes.length); // 打印图片数据长度
            return imageBytes;
        }
    }

    public static byte[] createZipFile(byte[] fileBytes, String fileName) throws IOException {
        try(ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(baos))){
            for (int i = 0; i < 10; i++) {
                try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(fileBytes));) {
                    ZipEntry zipEntry = new ZipEntry(i + "_" + fileName);
                    zos.putNextEntry(zipEntry);
                    byte[] buf = new byte[8192];
                    int len;
                    // 判断流中的数据不为0将文件添加到压缩包
                    while ((len = bis.read(buf)) > 0) {
                        zos.write(buf, 0, len);
                    }
                    zos.closeEntry();
                }
            }
            zos.closeEntry();
            zos.finish();
            zos.flush();
            return baos.toByteArray();
        }
    }

    public static void main(String[] args) {
        String imageUrl = "http://image.izehui.com/CPMS/20231216/13ed3288902b6486290bc4df43732c91.jpg"; // 替换为实际的图片URL
        String zipFilePath = "images.zip"; // 压缩包的输出路径

        try {
            // 下载图片
            byte[] imageBytes = downloadImage(imageUrl);

            // 创建压缩包并添加图片
            byte[] zipBytes = createZipFile(imageBytes, "image.jpg");

            // 验证压缩包的完整性
            try (FileOutputStream fos = new FileOutputStream(zipFilePath)) {
                fos.write(zipBytes);
            }

            System.out.println("图片已成功下载并打包到 " + zipFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
